/*
* Copyright (C) Microsoft. All rights reserved.  
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not 
* use this file except in compliance with the License.  You may obtain a copy 
* of the License at http://www.apache.org/licenses/LICENSE-2.0  
* 
* THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 
* WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 
* MERCHANTABLITY OR NON-INFRINGEMENT. 
*
* See the Apache License, Version 2.0 for specific language governing 
* permissions and limitations under the License.
*
*/
#pragma once

#include <baja/common.hpp>
#include <baja/diagnostics_config.hpp>

// configuration
// BAJA_CONFIG_TRACE_USE_DEBUG - define this to dump traces to the debug output
// BAJA_CONFIG_TRACE_USE_CONSOLE - define this to dump traces to the console

// try to use debug output by default
#if !defined(BAJA_CONFIG_TRACE_USE_CONSOLE) && !defined(BAJA_CONFIG_TRACE_USE_DEBUG)
#define BAJA_CONFIG_TRACE_USE_DEBUG
#endif

// if can't use debug output version, correct it
#if defined(BAJA_CONFIG_TRACE_USE_DEBUG) && (!defined(BAJA_WIN32))
#pragma message("debug output not supported, using console for trace output")
#undef BAJA_CONFIG_TRACE_USE_DEBUG
#endif

#ifdef BAJA_CONFIG_TRACE_USE_DEBUG
#include <Windows.h>
#else
#include <iostream>
#endif

namespace baja
{

// note trace doesn't support wide char messages (i.e. anything that can be streamed into an ostringstream)
// anything else will give compilation errors
template<class Tmsg> BAJA_INLINE void bajaTrace(const Tmsg& msg, const bool undecorated = false)
{
#ifdef BAJA_CONFIG_TRACE_USE_DEBUG
    // we use a string stream so we can leverage the << operator which should already be 
    // wired up to take in strings, boost::format, char* and any other types we care about 
    std::ostringstream outs;
#ifdef BAJA_CONFIG_TRACE_PREFIX
    if (!undecorated)
    {
        outs << BAJA_CONFIG_TRACE_PREFIX;
    }
#endif
    outs << msg << '\n';
    std::string str = outs.str();

#ifdef BAJA_DEBUG
	OutputDebugStringA(str.c_str());
#endif
#else
    std::cout << msg << '\n';
#endif
}

#ifdef BAJA_CONFIG_ENABLE_TRACING
#define BAJA_TRACE(msg) baja::bajaTrace(msg)
#else
#define BAJA_TRACE(msg) ((void)0)
#endif

} // namespace baja
